<?php
namespace app\api\service;
use think\Controller;
use think\Db;

class Cart extends Controller {
    static protected $err_code = 0;
    //购物车添加产品接口
    static public function save_cart_product($param) {

        if( !isset($param['member_id']) || !isset($param['product_id']) || !isset($param['product_name'])
            || !isset($param['product_img']) || !isset($param['product_num'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{
            $where = [
                'member_id' => $param['member_id']
                ,'product_id' => $param['product_id']
            ];
            $rs = Db::table('mob_cart')->where($where)->select();
            if( $rs ){
                $product_num_new = $rs["product_num"] + $param['product_num'];
                if($product_num_new>0){
                    $data = [
                        'product_num' => $product_num_new
                    ];
                    $rs_update = Db::table('mob_cart')->where("id",$rs['id'])->update($data);
                    if($rs_update){
                        $insert_id = $rs['id'];
                    }
                } else {
                    self::$err_code = 400079;
                    throw new \Exception('FAULT');
                }
            }else{
                $data = [
                    'member_id' => $param['member_id']
                    ,'product_id' => $param['product_id']
                    ,'product_name' => $param['product_name']
                    ,'product_img' => $param['product_img']
                    ,'product_num' => ($param['product_num']?$param['product_num']:1)
                    ,'apply_time' => time()
                ];
                $insert_id = Db::table('mob_cart')->insertGetId($data);
            }
            // 提交事务
            Db::commit();
            return ['data'=>['server_demand_id' => $insert_id],'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }


    // 删除购物车产品接口
    static public function del_cart_product($param){
        if (!isset($param['member_id']) || !isset($param['product_id']) ) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{
            $where = [
                'member_id' => $param['member_id']
                ,'product_id' => $param['product_id']
            ];
            $rs = Db::table('mob_cart')->where($where)->delete();
            Db::commit();
            return ['code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>0,'msg'=> $e->getMessage()];
        }

    }


}





